import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:plugin_asr/entity/flow_tts_entity.dart';
import 'package:plugin_asr/plugin_asr.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> implements AsrObserver {
  final _pluginAsrPlugin = PluginAsr();
  final TextEditingController _controller = TextEditingController();

  int _initRet = -1;
  String _asrResult = "";
  // String _text = "科大讯飞成立于1999年，总部位于合肥，是中国人工智能领域领军企业，专注智能语音、自然语言处理及认知智能技术研发。其语音合成、语音识别等核心能力国际领先，产品覆盖教育、医疗、办公等领域，赋能全球开发者超600万，系亚太地区最具价值AI企业之一";
  String _text = "iFlytek was founded in 1999 with its headquarters in Hefei. As a leading enterprise in China's artificial intelligence sector, it specializes in the research and development of intelligent voice, natural language processing, and cognitive intelligence technologies. The company's core capabilities in speech synthesis and speech recognition rank among the world's best. Its products span education, healthcare, office applications, and other fields, empowering over 6 million developers globally. iFlytek is recognized as one of the most valuable AI companies in the Asia-Pacific region.";
  bool isPersonTTSRunning = false;

  @override
  void initState() {
    super.initState();
    _pluginAsrPlugin.attach(this);
    _initAsrPlugin();
    _controller.text = _text;
  }

  @override
  void dispose() {
    _pluginAsrPlugin.detach(this);
    _controller.dispose();
    super.dispose();
  }

  Future<void> _initAsrPlugin() async {
    try {
      final ret = await _pluginAsrPlugin.init(
        "93d2c835",
        "90f654e8f51841ea849e65e5618a75fb",
        "NjQ5ZjJiNzQzNGZlODFhMWY3NGRmY2U1",
      );
      if (ret != null) {
        setState(() {
          _initRet = ret;
        });
      }
    } catch (e) {
      debugPrint('ASR初始化失败: $e');
      setState(() {
        _initRet = -1;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: SingleChildScrollView(
          child: Center(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  _buildInitStatus(),
                  _buildAsrResultDisplay(),
                  _buildStartAsrButton(),
                  _buildStopAsrButton(),
                  const SizedBox(height: 16),
                  _buildTextInput(),
                  _buildTtsButtons(),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildInitStatus() {
    return Text(
      '初始化结果: ${_initRet == 0 ? '成功' : '失败'}',
      style: const TextStyle(fontSize: 16),
    );
  }

  Widget _buildAsrResultDisplay() {
    return Text(
      '语音识别结果: ${_asrResult.isEmpty ? "--" : _asrResult}',
      style: const TextStyle(fontSize: 16),
    );
  }

  Widget _buildStartAsrButton() {
    return _buildActionButton('开始监听语音', _startAsrListener);
  }

  Widget _buildStopAsrButton() {
    return _buildActionButton('结束监听语音', _stopAsrListener);
  }

  Widget _buildTextInput() {
    return TextField(
      maxLines: 3,
      controller: _controller,
      decoration: const InputDecoration(
        border: OutlineInputBorder(),
        labelText: '输入要合成的文本',
      ),
      onChanged: (value) {
        _text = value;
      },
    );
  }

  Widget _buildTtsButtons() {
    return Column(
      children: [
        _buildActionButton('语音合成', _startOnlineTTS),
        _buildActionButton('结束语音合成', _stopOnlineTTS),
        _buildActionButton('拟人语音合成', _startPersonTTS),
        _buildActionButton('流式拟人语音合成', _startFlowPersonTTS),
        _buildActionButton('结束拟人语音合成', _stopPersonTTS),
      ],
    );
  }

  Widget _buildActionButton(String text, VoidCallback onPressed) {
    return SizedBox(
      width: 150,
      child: MaterialButton(
        color: Colors.blue,
        onPressed: onPressed,
        child: Text(
          text,
          style: const TextStyle(color: Colors.white),
        ),
      ),
    );
  }

  Future<void> _startAsrListener() async {
    try {
      // zh_cn:中文，en_us:英文。其他语种参见集成文档
      final res = await _pluginAsrPlugin.startAsrListener("en_us");
      if (res != null) {
        setState(() {
          _asrResult = res;
        });
      }
    } catch (e) {
      debugPrint('开始语音识别失败: $e');
    }
  }

  Future<void> _stopAsrListener() async {
    try {
      await _pluginAsrPlugin.stopAsrListener();
    } catch (e) {
      debugPrint('停止语音识别失败: $e');
    }
  }

  Future<void> _startOnlineTTS() async {
    try {
      await _pluginAsrPlugin.startOnlineTTS(_text);
    } catch (e) {
      debugPrint('开始在线TTS失败: $e');
    }
  }

  Future<void> _stopOnlineTTS() async {
    try {
      await _pluginAsrPlugin.stopOnlineTTS();
    } catch (e) {
      debugPrint('停止在线TTS失败: $e');
    }
  }

  Future<void> _startPersonTTS() async {
    try {
      int? res = await _pluginAsrPlugin.startPersonTTS(_text);
      debugPrint("语音合成并播放完成:$res");

    } catch (e) {
      debugPrint('开始拟人TTS失败: $e');
    }
  }

  Future<void> _startFlowPersonTTS() async {
    String texts = _text;
    int status = 0; // 输入文本状态，0:开始，1:中间，2:结束
    if (isPersonTTSRunning) return;
    isPersonTTSRunning = true;
    // 模拟流式文本
    for (int i = 0; i < texts.length; i++) {
      if (isPersonTTSRunning == false) {
        break;
      }
      if (i == 0) {
        status = 0;
      } else if (i == texts.length - 1) {
        isPersonTTSRunning = false;
        status = 2;
      } else {
        status = 1;
      }
      try {
        FlowTtsEntity flowTtsEntity = FlowTtsEntity(
            text: texts[i],
            status: status
        );
        if(flowTtsEntity.status == 2) {
          var res = await _pluginAsrPlugin.startFlowPersonTTS(flowTtsEntity);
          debugPrint("语音合成并播放完成:$res");
        } else {
          var res = await _pluginAsrPlugin.startFlowPersonTTS(flowTtsEntity);
          if(res != 0) {
            debugPrint("语音合成并播放失败:$res");
            break;
          }
        }
        await _delay(100);
      } catch (e) {
        debugPrint('开始流式拟人TTS失败: $e');
        break;
      }
    }
  }

  // 封装 delay 方法
  Future<void> _delay(int milliseconds) {
    return Future.delayed(Duration(milliseconds: milliseconds));
  }

  Future<void> _stopPersonTTS() async {
    try {
      isPersonTTSRunning = false;
      await _pluginAsrPlugin.stopPersonTTS();
    } catch (e) {
      debugPrint('停止拟人TTS失败: $e');
    }
  }

  @override
  void onAsrData(MethodCall call) {
    if (call.method == AsrEvent.asrListenerProcess.name) {
      setState(() {
        _asrResult = call.arguments;
      });
    }
  }
}